package com.lm.caffeine.example;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.concurrent.TimeUnit;

public class CacheExample {
    public static void main(String[] args) {
        // 创建缓存实例
        Cache<String, String> cache = Caffeine.newBuilder()
                .maximumSize(100) // 最大条目数
                .expireAfterWrite(5, TimeUnit.MINUTES) // 写入后 5 分钟过期
                .build();

        // 添加缓存
        cache.put("user:1", "John Doe");

        // 获取缓存
        String value = cache.getIfPresent("user:1");
        System.out.println("从缓存获取的值: " + value);

        // 缓存过期后返回 null
        try {
            Thread.sleep(TimeUnit.MINUTES.toMillis(6));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        value = cache.getIfPresent("user:1");
        System.out.println("过期后获取的值: " + value);
    }
}
